package com.learning.mediacomponent;

import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.documentfile.provider.DocumentFile;

import java.io.IOException;
import java.util.Timer;

public class PlayingRecordActivity extends AppCompatActivity implements View.OnClickListener {

    private MediaPlayer player;
    private ActivityResultLauncher<Intent> selectAudioFileLauncher;

    private long currentDuration;
    private Uri audioUri;
    private TextView tvFileName;
    private Button selectFile, pausePlayingButton, exitPlayingButton;

    private boolean isPlaying = false;
    private Handler handler;
    protected SeekBar seekBar; //进度条
    private Timer timer;  //定时器
    protected TextView tvStart;  //开始时间
    protected TextView tvEnd;  //结束时间
    private boolean isSeekbarChaning;  //互斥变量，防止进度条和定时器冲突。

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_playing_record);
//        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
//            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
//            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
//            return insets;
//        });

        // 初始化 ActivityResultLauncher
        selectAudioFileLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK) {
                        Intent data = result.getData();
                        if (data != null && data.getData() != null) {
                            audioUri = data.getData();
                            DocumentFile documentFile = DocumentFile.fromSingleUri(this, audioUri);
                            tvFileName.setText(documentFile.getName());
                            startPlaying(audioUri);
                            Log.i("选择的录音文件路径", "onCreate: " + audioUri.toString());
                        }
                    }
                }
        );

        selectFile = findViewById(R.id.btn_select_file);
        pausePlayingButton = findViewById(R.id.btn_pause_playing); //暂停
        exitPlayingButton = findViewById(R.id.btn_exit_playing); //取消
        tvFileName = findViewById(R.id.tv_file_name);
        tvStart = findViewById(R.id.tv_start);
        tvEnd = findViewById(R.id.tv_end);
        seekBar = findViewById(R.id.seekbar);

        // Set initial state
        pausePlayingButton.setEnabled(false);
        exitPlayingButton.setEnabled(false);

        selectFile.setOnClickListener(this);
        pausePlayingButton.setOnClickListener(this);
        exitPlayingButton.setOnClickListener(this);

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && player != null) {
                    player.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isSeekbarChaning = false;
                if (player != null) {
                    player.seekTo(seekBar.getProgress());//在当前位置播放
                    tvStart.setText(millisecondsToTime(player.getCurrentPosition()));
                }
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        // Handler to update SeekBar and time TextViews
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (player != null) {
                    int currentPosition = player.getCurrentPosition();
                    int totalDuration = player.getDuration();

                    seekBar.setMax(totalDuration);
                    seekBar.setProgress(currentPosition);

                    // Update TextViews
                    tvStart.setText(millisecondsToTime(currentPosition));
                    tvEnd.setText(millisecondsToTime(totalDuration));

                    // Update SeekBar and TextViews every 100 milliseconds
                    handler.sendEmptyMessageDelayed(0, 100);
                }
                return true;
            }
        });
    }



    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_select_file) {
            if (player != null) {
                stopPlaying();
            }
            openFilePicker();
        } else if (v.getId() == R.id.btn_pause_playing) {
            if (player != null && player.isPlaying()) {
                player.pause();
                isPlaying = false;
                pausePlayingButton.setText("继续播放");
            } else {
                player.start();
                isPlaying = true;
                pausePlayingButton.setText("暂停播放");
                updateSeekBar();
            }
        } else if (v.getId() == R.id.btn_exit_playing) {
            stopPlaying();
        }
    }

    // 启动文件选择器
    private void openFilePicker() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("audio/Music/Recordings/*");
        selectAudioFileLauncher.launch(intent);
    }

    private void startPlaying(Uri fileUri) {
        try {
            player = new MediaPlayer();
            player.setDataSource(this, fileUri);
            player.prepare();
            player.start();
            isPlaying = true;
            pausePlayingButton.setEnabled(true);
            exitPlayingButton.setEnabled(true);
            updateSeekBar();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "无法播放文件", Toast.LENGTH_SHORT).show();
        }
    }

    private void updateSeekBar() {
        if (player != null) {
            handler.sendEmptyMessage(0);
        }
    }


    private String millisecondsToTime(int milliseconds) {
        int seconds = milliseconds / 1000;
        int minutes = seconds / 60;
        seconds = seconds % 60;
        return String.format("%d:%02d", minutes, seconds);
    }

    private void stopPlaying(){
        if (player != null) {
            player.stop();
            player.release();
            player = null;
            isPlaying = false;
            pausePlayingButton.setEnabled(false);
            exitPlayingButton.setEnabled(false);
            currentDuration = 0;
            seekBar.setProgress(0);
            tvStart.setText(millisecondsToTime(0));
            tvEnd.setText(millisecondsToTime(0));
            tvFileName.setText("文件名称");
            pausePlayingButton.setText("暂停播放");
//            Toast.makeText(this, "停止播放", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.release();
            player = null;
        }
        handler.removeCallbacksAndMessages(null);
    }


}